/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2006.
 *
 * Licensed under the Aduna BSD-style license.
 */
package edu.tju.commons.concurrent;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Herko ter Horst
 */
public class ConfigurableThreadFactory implements ThreadFactory {

	private static final AtomicInteger poolNumber = new AtomicInteger(1);

	private final ThreadGroup group;

	private final AtomicInteger threadNumber = new AtomicInteger(1);

	private final String namePrefix;

	public ConfigurableThreadFactory(int priority, boolean daemon) {
		SecurityManager s = System.getSecurityManager();
		group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
		
		group.setMaxPriority(priority);
		group.setDaemon(daemon);
		
		namePrefix = "configurablepool-" + poolNumber.getAndIncrement() + "-thread-";
	}

	public Thread newThread(Runnable task) {
		Thread result = new Thread(group, task, namePrefix + threadNumber.getAndIncrement());
		result.setDaemon(group.isDaemon());
		return result;
	}

}
